package com.coder520.servicestudy;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

/**
 * Created by huang on 2017/7/6.
 */

public class MainActivity2 extends Activity {
    private static final String TAG = MainActivity2.class.getSimpleName();
    private StudentService mStudentService;
    private boolean mServiceBinded = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.btn_bindService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity2.this, StudentService.class);
                bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
                mServiceBinded = true;
            }
        });
        findViewById(R.id.btn_unbindService).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(mServiceConnection);
                mServiceBinded = false;
            }
        });
        findViewById(R.id.btn_jump).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity2.this, MainActivity.class);
                startActivity(intent);
            }
        });
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mStudentService = ((StudentService.MyBinder)service).getService();
            Log.d(TAG, "code520 student is:" + mStudentService.getStudent());
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mStudentService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mServiceBinded) {
            unbindService(mServiceConnection);
        }
    }
}
